package com.mission.schedule.service

import android.app.Service
import android.content.Intent
import android.os.IBinder
import android.content.IntentFilter
import com.mission.schedule.constants.ShareFile
import com.mission.schedule.receiver.MTimeReceiver
import com.mission.schedule.utils.SharedPrefUtil


/**
 * Created by liwei on 2017/11/30.
 */
class MTimeService : Service() {
    private var enabled = false
    private var receiver: MTimeReceiver? = null
    private lateinit var sharep: SharedPrefUtil

    override fun onBind(intent: Intent) = null

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        sharep = SharedPrefUtil(applicationContext, ShareFile.USERFILE)
        if (sharep.getString(applicationContext, ShareFile.USERFILE, ShareFile.ISTX, "1") == "0") {
            receiver = MTimeReceiver()
            val timeFilter = IntentFilter()
            timeFilter.addAction(Intent.ACTION_TIME_TICK)
            registerReceiver(receiver, timeFilter)
        }
        return if (enabled) {
            START_STICKY
        } else {
            super.onStartCommand(intent, flags, startId)
        }
    }

    override fun onDestroy() {
        if (receiver != null) {
            unregisterReceiver(receiver)
        }
        if (enabled) {
            var intent = Intent(applicationContext, MTimeService::class.java)
            startService(intent)
            return
        }
        super.onDestroy()
    }
}